#coding=utf-8

from google.appengine.ext import db
import random

class CounterShard(db.Model):
  """Shards for the counter"""
  count = db.IntegerProperty(required=True, default=0)   

NUM_SHARDS = 20

def get_count():
  """Retrieve the value for a given sharded counter."""
  total = 0
  for counter in CounterShard.all():
    total += counter.count
  return total
   
def change_count(delta):
  """change the value for a given sharded counter by delta."""
  def txn():
    index = random.randint(0, NUM_SHARDS - 1)
    shard_name = "shard" + str(index)
    counter = CounterShard.get_by_key_name(shard_name)
    if counter is None:
      counter = CounterShard(key_name=shard_name)
    
    counter.count += delta
    counter.put()
    
  db.run_in_transaction_custom_retries(10, txn)
